package cn.itheima.servlet;

import cn.itheima.bean.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

@WebServlet("/addStudent")
public class addStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*设置内容编码*/
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        /*获取添加学生表单信息*/
        Map<String, String[]> map = req.getParameterMap();
        /*创建学生对象*/
        Student stu = new Student();
        /*工具类封装学生信息*/
        try {
            BeanUtils.populate(stu,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*将学生信息写入本地文件*/
        /*创建高效字符输出流*/
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\stu.txt", true));
        bw.write(stu.toString());
        bw.newLine();
        bw.close();
        //通过定时刷新功能响应给浏览器
        resp.getWriter().write("添加成功。2秒后自动跳转到首页...");
        resp.setHeader("Refresh", "2;URL=/stu/index.jsp");
    }
}
